package ${webPackageName}.handler;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import ${commonPackageName}.entity.resp.CommonRsp;
import ${commonPackageName}.entity.resp.Result;
import ${commonPackageName}.exception.BusinessException;
import ${webPackageName}.constant.ScanPackageConstant;

import lombok.extern.slf4j.Slf4j;



/**
 * 全局异常处理&统一返回格式
 * @author lizihao
 *
 */
<#noparse>
@ControllerAdvice(basePackages = ScanPackageConstant.GLOBAL_EXCEPTION_SCAN)
@Slf4j
public class GlobalExceptionHandler implements ResponseBodyAdvice<Object>{
	
	   @ExceptionHandler(value=Exception.class)
	   @ResponseBody
	   public <T>CommonRsp<T> handleException(Exception e){
		   log.error("异常信息 {}",e.getMessage());
		   			e.printStackTrace();
		   			return CommonRsp.fail("系统繁忙");
	     }
	   
	   @ExceptionHandler(value=IllegalArgumentException.class)
	   @ResponseBody
	   public <T>CommonRsp<T> illegalArgumentException(IllegalArgumentException e){
		   log.error("异常信息{}",e.getMessage());
	   		return CommonRsp.fail(e.getMessage()) ;
	     }
	   
	   @ExceptionHandler(value=BusinessException.class)
	   @ResponseBody
	   public <T>CommonRsp<T> handleBusinessException(BusinessException e){
		   log.error("异常信息{}",e.getExceptionEnum().getMsg());
	   		return CommonRsp.fail(e.getExceptionEnum()) ;
	     }

	   @ExceptionHandler(value=MethodArgumentNotValidException.class)
	   @ResponseBody
	   public <T>CommonRsp<T> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
		   	FieldError fieldError = e.getBindingResult().getFieldError();
		   	log.error("异常信息{}",fieldError.getField()+fieldError.getDefaultMessage());
		            return CommonRsp.fail(fieldError.getField()+fieldError.getDefaultMessage());
	     }

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	/**
	 * 返回前拦截,统一返回格式
	 */
	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		CommonRsp<Object> rep = new CommonRsp<>();
		rep.setData(body);
		rep.setResult(Result.ok());
		return rep;
	}
}
</#noparse>